import os
import sys
import qrcode
from PIL import Image

def gen_qrcode(data):
    iconPath = '20170711162412.jpg'
    qr = qrcode.QRCode(version = 2, error_correction = qrcode.constants.ERROR_CORRECT_H, box_size = 10, border = 1)
    qr.add_data(data)
    qr.make(fit=True)
    # 生成二维码图片
    qrcode_img = qr.make_image()
    qrcode_img = qrcode_img.convert('RGBA')
    if os.path.isfile(iconPath):
        # 二维码中间的头像
        icon = Image.open(iconPath)
        icon = icon.convert('RGBA')
        qrcode_img_w, qrcode_img_h = qrcode_img.size
        factor = 4
        size_w = int(qrcode_img_w / factor)
        size_h = int(qrcode_img_h / factor)
        icon_w, icon_h = icon.size
        if icon_w > size_w:
            icon_w = size_w
        if icon_h > size_h:
            icon_h = size_h
        # 头像缩小为二维码的四分之一
        icon = icon.resize((icon_w, icon_h), Image.ANTIALIAS)
        # 把头像放置中间
        w = int((qrcode_img_w - icon_w) / 2)
        h = int((qrcode_img_h - icon_h) / 2)
        qrcode_img.paste(icon, (w, h), icon)
    qrcode_img.save('qrcode.png', quality=100)
    print('二维码已生成')
    qrcode_img.show()

if __name__ == '__main__':
    if len(sys.argv) == 2:
        gen_qrcode(sys.argv[1])
    else:
        print('用法：python erweima.py 数据')

